<?php
require_once(dirname(__FILE__).'/Abstract.php');
class Prescription extends AbstractDoctorController 
{
    public function indexAction()
    {
    	$this->listingAction();
    }

    public function listingAction()
    {
    	
        $d = array();
        $d['title'] = $this->l('List of prescriptions');
        $d['prescriptions'] = $this->getAllPrescriptions($this->session->userdata('id_user'));

        $d['title_for_layout'] = $this->l('prescriptions list.');
        $d['menu'] = 'patients';
        $d['page_name'] = 'prescriptions_list';
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Prescription/Listing', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);

    }

    public function createAction()
    {
    	$d = array();
        $d['title'] = $this->l('Create a prescription');

        if ($this->input->post('btn_submit') !== false){
             // Initialized the form validation
            $config = array(
               array(
                     'field'   => 'id_consultation', 
                     'label'   => $this->l('Consultation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'content', 
                     'label'   => $this->l('Content'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == FALSE ){
                $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
                // $this->load->model('ORM/Consultation/ConsultationPrescriptionORM');
                // Initialize the new record
                $record = array(
                    'content'        => $this->input->post('content'),
                    'id_consultation'=> $this->input->post('id_consultation'),                   
                    // Automatic fill                           
                    'status'        => 1,
                    'date_add'       => @date('Y-m-d H:i:s'),
                    'date_upd'       => @date('Y-m-d H:i:s'),
                );
                // Create the new prescription
                if ($this->ConsultationPrescriptionORM->save($record)) {
                    // Redirect to the sign in form
                    redirect('Doctor/Prescription/listing');
                    die();
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving your prescription. Please try again.'));
                }
            }
        } 

        $d['consultations'] = $this->getAllConsultations($this->session->userdata('id_user'));
 

        $d['title_for_layout'] = $this->l('Creating a prescription.');
        $d['menu'] = 'prescriptions';
        $d['page_name'] = 'creating_prescription';
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Prescription/Create', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);
    }

    public function updateAction($id_prescription = NULL)
    {
    	$d = array();
        $d['title'] = $this->l('Update a prescription');

        if ($this->input->post('btn_submit') !== false){
             // Initialized the form validation
            $config = array(
            	array(
                     'field'   => 'id_prescription', 
                     'label'   => $this->l('Consultation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               	array(
                     'field'   => 'id_consultation', 
                     'label'   => $this->l('Consultation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               	array(
                     'field'   => 'content', 
                     'label'   => $this->l('Content'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               	array(
                     'field'   => 'status', 
                     'label'   => $this->l('Status'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == FALSE ){
                $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
                // $this->load->model('ORM/Consultation/ConsultationPrescriptionORM');
                // Initialize the new record
                $record = array(
                    'id_prescription'=> $this->input->post('id_prescription'),
                    'id_consultation'=> $this->input->post('id_consultation'),  
                    'content'        => $this->input->post('content'),
                    'status'         => $this->input->post('status'),                 
                    // Automatic fill 
                    'date_add'       => @date('Y-m-d H:i:s'),
                    'date_upd'       => @date('Y-m-d H:i:s'),
                );
                // Create the new prescription
                if ($this->ConsultationPrescriptionORM->save($record)) {
                    // Redirect to the sign in form
                    redirect('Doctor/Prescription/listing');
                    die();
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving your prescription. Please try again.'));
                }
            }
        } 

        $d['prescription'] = $this->getPrescriptionById($id_prescription);
        // Read all other consultations of this doctor
        $d['consultations'] = $this->getAllConsultations($this->session->userdata('id_user'));

        $d['title_for_layout'] = $this->l('Updating a prescription.');
        $d['menu'] = 'prescriptions';
        $d['page_name'] = 'updating_prescription';
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Prescription/Update', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);
    }

    public function sendAction()
    {
        $d = array();
        $d['title'] = $this->l('Send a prescription');

        $d['prescriptions'] = $this->getAllPrescriptions($this->session->userdata('id_user'));
        // $this->load->model('ORM/User/UserPatientORM');
        $d['patients'] = $this->UserPatientORM->getAllBy();
 
        $d['title_for_layout'] = $this->l('Sending a prescription.');
        $d['menu'] = 'prescriptions';
        $d['page_name'] = 'sending_prescription';

        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Prescription/Send', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);
    }

    public function stopAction($id_prescription)
    {

        // $this->load->model('ORM/Consultation/ConsultationPrescriptionORM');
        $record = array(
            'id_prescription'=> $id_prescription,
            'status'         => '0',
            'date_upd'       => @date('Y-m-d H:i:s'),
            );
        // Set the prescription status to off
        if ($this->ConsultationPrescriptionORM->save($record)) {
            // Redirect to the prescriptions list
            redirect('Doctor/Prescription/listing');
            die();
        } else {
            $this->session->set_flashdata('errorMessage', $this->l('An error occured while stopping your prescription. Please try again.'));
            redirect('Doctor/Prescription/listing');
            die();
        }
    }
    
    /* ==================================================
     *
     * PROTECTED FUNCTIONS
     * 
     * ================================================== */
    protected function getAllPrescriptions($id_doctor)
    {
                
        $prescription_table         = $this->ConsultationPrescriptionORM->getTableName();
        $prescription_table_primary = $this->ConsultationPrescriptionORM->getPrimaryKey();
        $cons_table                 = $this->ConsultationORM->getTableName();        
        $cons_table_primary         = $this->ConsultationORM->getPrimaryKey();
        $users_table                = $this->UserEntityORM->getTableName();        
        $users_table_primary        = $this->UserEntityORM->getPrimaryKey();
        $patients_table             = $this->UserPatientORM->getTableName();        
        $patients_table_primary     = $this->UserPatientORM->getPrimaryKey();
        
        //TODO : Enumarate fields to select because of date add 
        $this->db->select('precr.*, cons.*, users.*');
        $this->db->from($prescription_table.' as precr');
        $this->db->join($cons_table.' as cons', 'cons.'.$cons_table_primary.'='.'precr.'.$cons_table_primary, 'left');
        $this->db->join($users_table.' as users', 'cons.'.$patients_table_primary.'='.'users.'.$users_table_primary, 'left');
        $this->db->where('cons.id_doctor = '. (int)$id_doctor);
        
        $query = $this->db->get();

        return $query->result();
    }

    protected function getAllConsultations($id_doctor)
    {
        
        $prescription_type_table = $this->ConsultationTypeORM->getTableName();
        $prescription_type_table_primary = $this->ConsultationTypeORM->getPrimaryKey();
        
        //TODO : Join with the consultation type lang table 
        $cons_table             = $this->ConsultationORM->getTableName();        
        $cons_table_primary     = $this->ConsultationORM->getPrimaryKey();
        $users_table            = $this->UserEntityORM->getTableName();        
        $users_table_primary    = $this->UserEntityORM->getPrimaryKey();
        $patients_table         = $this->UserPatientORM->getTableName();        
        $patients_table_primary = $this->UserPatientORM->getPrimaryKey();
        
        $this->db->select('cons.*, users.*, cons_type.*');
        $this->db->from($cons_table.' as cons');
        $this->db->join($users_table.' as users', 'cons.'.$patients_table_primary.'='.'users.'.$users_table_primary, 'left');
        $this->db->join($prescription_type_table.' as cons_type', 'cons.'.$prescription_type_table_primary.'='.'cons_type.'.$prescription_type_table_primary, 'left');
        $this->db->where('cons.id_doctor = '. (int)$this->session->userdata('id_user'));
        $query = $this->db->get();

        return $query->result();
    }

    protected function getPrescriptionById($id_prescription)
    {
        
        $prescription_table         = $this->ConsultationPrescriptionORM->getTableName();
        $prescription_table_primary = $this->ConsultationPrescriptionORM->getPrimaryKey();
        $cons_table                 = $this->ConsultationORM->getTableName();        
        $cons_table_primary         = $this->ConsultationORM->getPrimaryKey();
        $users_table                = $this->UserEntityORM->getTableName();        
        $users_table_primary        = $this->UserEntityORM->getPrimaryKey();
        $patients_table             = $this->UserPatientORM->getTableName();        
        $patients_table_primary     = $this->UserPatientORM->getPrimaryKey();
        
        //TODO : Enumerate fields to select because of date add 
        $this->db->select('precr.*, cons.*, users.*');
        $this->db->from($prescription_table.' as precr');
        $this->db->join($cons_table.' as cons', 'cons.'.$cons_table_primary.'='.'precr.'.$cons_table_primary, 'left');
        $this->db->join($users_table.' as users', 'cons.'.$patients_table_primary.'='.'users.'.$users_table_primary, 'left');
        $this->db->where('precr.id_prescription = '.$id_prescription);
        $query = $this->db->get();

        return $query->row_array();
    }
}

